package com.ruoyi.system.pool;

import com.jcraft.jsch.Session;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.pool2.impl.GenericKeyedObjectPoolConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PreDestroy;

/**
 * @description: 对象池配置
 * @author: stone
 * @date: Created by 2022/4/16 17:52
 * @version: 1.0.0
 * @pakeage: com.ruoyi.system.pool
 */
@Configuration
@EnableConfigurationProperties(SshPoolProperties.class)
@Slf4j
public class SshPoolConfig {

    private SshPoolProperties sshPoolProperties;

    private SshClientPool keyPool;

    @Autowired
    private SshClientFactory factory;

    public SshPoolConfig(SshPoolProperties sshPoolProperties) {
        this.sshPoolProperties = sshPoolProperties;
    }

    @Bean
    @ConditionalOnClass(SshClientFactory.class)
    protected SshClientPool keyObjectPool() {
        //SshClientFactory factory = new SshClientFactory();
        GenericKeyedObjectPoolConfig<Session> config = new GenericKeyedObjectPoolConfig<>();
        // 多个key组 总最大数
        config.setMaxTotal(sshPoolProperties.getMaxTotalKey() * 20);
        // 一个key组 最大数
        config.setMaxTotalPerKey(sshPoolProperties.getMaxTotalKey());
        // 一个key组 最大空闲数
        config.setMaxIdlePerKey(sshPoolProperties.getMaxIdleKey());
        // 一个key组 最小空闲数
        config.setMinIdlePerKey(sshPoolProperties.getMinIdleKey());
        config.setBlockWhenExhausted(true);
        config.setTestOnReturn(true);
        config.setTestOnBorrow(true);
        config.setTestWhileIdle(true);
        config.setTimeBetweenEvictionRunsMillis(1000L * 60 * 30);
        config.setJmxEnabled(false);

        keyPool = new SshClientPool(factory, config);
        //initKeyPool(sshPoolProperties.getInitialSize(),sshPoolProperties.getMaxIdle());
        return keyPool;

    }


    @PreDestroy
    public void destroy() {
        log.info("ssh对象池关闭-start");
        if (null != keyPool) {
            keyPool.close();
        }
        if (null != keyPool) {
            keyPool.close();
        }
        log.info("ssh对象池关闭-end");
    }


}
